package com.baixun.gassystem.service;

import com.baixun.gassystem.mapper.SysDepartmentRolePermissionsMapper;
import com.baixun.gassystem.mapper.SysDepartmentRolesMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: 上海燃气驾驶舱
 * @description: 创建一个权限加载服务类：这个服务类包含从数据库查询角色和权限的方法。
 * @author: yesong
 **/

@Service
public class AuthorityService {
    @Autowired
    private  SysDepartmentRolesMapper sysDepartmentRolesMapper;

    @Autowired
    private  SysDepartmentRolePermissionsMapper sysDepartmentRolePermissionsMapper;

    public AuthorityService(SysDepartmentRolesMapper sysDepartmentRolesMapper,
                            SysDepartmentRolePermissionsMapper sysDepartmentRolePermissionsMapper) {
        this.sysDepartmentRolesMapper = sysDepartmentRolesMapper;
        this.sysDepartmentRolePermissionsMapper = sysDepartmentRolePermissionsMapper;
    }

    public List<GrantedAuthority> getAuthoritiesByUserId(Long userId) {
        List<Long> roleIds = sysDepartmentRolesMapper.findRoleIdsByUserId(userId);
        List<GrantedAuthority> authorities = new ArrayList<>();

        for (Long roleId : roleIds) {
            // 将角色ID添加为权限（如有需要，也可以使用角色名称或自定义前缀）
            authorities.add(new SimpleGrantedAuthority("ROLE_" + roleId));

            // 获取该角色的权限
            List<String> permissions = sysDepartmentRolePermissionsMapper.findPermissionsByRoleId(roleId);
            for (String permission : permissions) {
                authorities.add(new SimpleGrantedAuthority(permission));
            }
        }
        return authorities;
    }
}
